package com.wanjia.estate.service.httpservice;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.wanjia.estate.pojo.bank.nxbank.PayStatus;
import com.wanjia.estate.pojo.bank.nxbank.ZhsdBszf;
import com.wanjia.estate.pojo.bank.nxbank.ZhsdZszf;
import com.wanjia.estate.properties.HttpRequestProperties;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 农信支付服务模块
 */
@Slf4j
@Service
public class NxHttpService extends AbstractHttpService {

    @Setter(onMethod_ = @Autowired)
    private HttpRequestProperties properties;

    @Autowired
    NxKeyService nxKeyService;

    /**
     * 农商行被扫支付
     *
     * @param request xml
     * @return
     * @throws Exception
     */
    public ZhsdBszf.ZhsdBszfReponse bszf(ZhsdBszf.ZhsdBszfRequest request) throws Exception {
        //ZhsdBszf.ZhsdBszfReponse
        log.debug("request body: {}", JSONUtil.toJsonStr(request));

        String xml = toXml(request);
        //加签后密文
        String nxAddKey = nxKeyService.NxAddKey(xml);
        int length = nxAddKey.getBytes().length;
        String encoded = String.format("%08d", length);

        String bszfUrl = properties.getBszfUrl();

        String response = null;

        try (Socket client = new Socket("192.168.2.14", 9003);
             OutputStream outToServer = client.getOutputStream();
             Writer writer = new OutputStreamWriter(outToServer);
             BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));) {


            log.info("真实请求：{}", encoded + nxAddKey);
            writer.write(encoded + nxAddKey);
            writer.flush();

            response = reader.readLine();
            System.out.println("收到服务器返回：" + response);
        } catch (UnknownHostException e) {
            System.err.println("未知的主机：");
        } catch (IOException e) {
            System.err.println("无法建立连接：" + e);
        }

        if (response != null && response.matches("\\d{8}.+")) {
            response = nxKeyService.NxDecryptKey(response.substring(8));
            log.debug("decrypt response: {}", response);
            return fromXml(response, ZhsdBszf.ZhsdBszfReponse.class);
        }

        throw new RuntimeException("响应解析异常");
    }

    /**
     * 农商行主扫支付
     *
     * @param request xml
     * @return
     * @throws Exception
     */
    public ZhsdZszf.ZhsdZszfResponse zszf(ZhsdZszf.ZhsdZszfRequest request) throws Exception {
        //ZhsdZszf.ZhsdZszfResponse
        log.debug("request body: {}", JSONUtil.toJsonStr(request));

        String xml = toXml(request);
        //加签后密文
        String nxAddKey = nxKeyService.NxAddKey(xml);
        int length = nxAddKey.getBytes().length;
        String encoded = String.format("%08d", length);
        String response = null;

        try (Socket client = new Socket("192.168.2.14", 9012);
             OutputStream outToServer = client.getOutputStream();
             Writer writer = new OutputStreamWriter(outToServer);
             BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));) {


            log.debug("真实请求：{}", encoded + nxAddKey);
            writer.write(encoded + nxAddKey);
            writer.flush();

            response = reader.readLine();
            log.debug("收到服务器返回：{}" , response);
        } catch (UnknownHostException e) {
            log.debug("未知的主机：");
        } catch (IOException e) {
            log.debug("无法建立连接" , e);
        }

        if (response != null && response.matches("\\d{8}.+")) {
            response = nxKeyService.NxDecryptKey(response.substring(8));
            log.debug("decrypt response: {}", response);
            return fromXml(response, ZhsdZszf.ZhsdZszfResponse.class);
        }

        throw new RuntimeException("响应解析异常");
    }

    /**
     * 农商行支付结果查询
     *
     * @param request xml
     * @return
     * @throws Exception
     */
    public PayStatus.PayStatusResponse payStatus(PayStatus.PayStatusRequest request) throws Exception {
        //PayStatus.PayStatusResponse
        log.debug("request body: {}", JSONUtil.toJsonStr(request));

        String xml = toXml(request);
        //加签后密文
        String nxAddKey = nxKeyService.NxAddKey(xml);
        int length = nxAddKey.getBytes().length;
        String encoded = String.format("%08d", length);
        String response = null;

        try (Socket client = new Socket("192.168.2.14", 9012);
             OutputStream outToServer = client.getOutputStream();
             Writer writer = new OutputStreamWriter(outToServer);
             BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));) {


            log.info("真实请求：{}", encoded + nxAddKey);
            writer.write(encoded + nxAddKey);
            writer.flush();

            response = reader.readLine();
            System.out.println("收到服务器返回：" + response);
        } catch (UnknownHostException e) {
            System.err.println("未知的主机：");
        } catch (IOException e) {
            System.err.println("无法建立连接：" + e);
        }

        if (response != null && response.matches("\\d{8}.+")) {
            response = nxKeyService.NxDecryptKey(response.substring(8));
            log.debug("decrypt response: {}", response);
            return fromXml(response, PayStatus.PayStatusResponse.class);
        }

        throw new RuntimeException("响应解析异常");
    }
}
